package dyyx;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.mvel2.MVEL;

public class Hello {

	public static void main(String[] args) throws Exception {	
		System.out.println("hello");	
		
		
		String expression = " (a + b + c*1.5) /3";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("a", 1);
		params.put("b", 2);
		params.put("c", 3);

		Object result = null;
		
		result = MVEL.eval(expression, params);
		
		System.out.println(result);
		System.out.println(result.getClass());
		
		try{
			params.put("c", "c");
			result = MVEL.eval(expression, params);
			System.out.println(result);
		}catch(Throwable e){
			System.out.println(e+"");
		}
		
		
		expression = " a + ',' + b + ',' + c ";
        result = MVEL.eval(expression, params);
		
		System.out.println(result);
		System.out.println(result.getClass());
		
		
		// expression = " a # b # c ";
        // result = MVEL.eval(expression, params);
		// System.out.println(result);

		
		//
		Serializable compiledExpression = null;
		// 表达式编译
		compiledExpression = MVEL.compileExpression(expression);
		
		result = MVEL.executeExpression(compiledExpression, params);
		
		System.out.println(result);
		
		
		
		System.out.println("******");
		
		expression = " int a=10; (a + b + c*1.5) /3";
		
		expression = " double x = dyyx.Utils.add(a,b) ; y = (x + c*1.5) /3 ; return y";

		params = new HashMap<String,Object>();
		params.put("a", 1);
		params.put("b", 2);
		params.put("c", 3);
		
		compiledExpression = MVEL.compileExpression(expression);
		
		result = MVEL.eval(expression, params);
		System.out.println(result);
		
        result = MVEL.executeExpression(compiledExpression, params);	
		System.out.println(result);
		
        // pre hot  预热
		
		Object result2 = null;
		
		final int  NUM = 100000;
		
		for(int i=0;i<NUM;i++){
			result = MVEL.eval(expression, params);
	        result2 = MVEL.executeExpression(compiledExpression, params);	

	        if(i>0 && i%10000 == 0){
	        	System.out.println(i+","+result+","+result2);
	        }

		}
		// TEST
		
		// 直接执行 耗时测试
		
		long start = System.currentTimeMillis();
		for(int i=0;i<NUM;i++){
			MVEL.eval(expression, params);
		}
		long end = System.currentTimeMillis();
		long time = end - start;
		
		System.out.println("MVEL.eval run time "+time);
		
		// 编译后执行 耗时测试
		
		start = System.currentTimeMillis();
		for(int i=0;i<NUM;i++){
			MVEL.executeExpression(compiledExpression, params);
		}
		end = System.currentTimeMillis();
		time = end - start;
		
		System.out.println("MVEL.executeExpression run time "+time);
		

        // MVEL.eval run time 11368
        // MVEL.executeExpression run time 714
		
		//  直接执行 耗时 11368 ms
		//  编译执行 耗时 714   ms

		
		
	}
	
	
	
	
	
}
